import 'dart:io';

import 'package:huxiaodui/api/api.dart';
import 'package:huxiaodui/api/app_update/ios_update.dart';
import 'package:huxiaodui/api/model/result.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:package_info_plus/package_info_plus.dart';

import 'app_update/android_update.dart';

class OtherApi {
  /// 单例模式
  static final OtherApi _instance = OtherApi._internal();
  factory OtherApi() {
    return _instance;
  }
  OtherApi._internal();

  Future<void> updateApp({isToast = false}) async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();

    await Api.request(
      url: OtherUrl.upload,
      data: {
        "appName": packageInfo.appName,
        "packageName": packageInfo.packageName,
        "version": packageInfo.version,
        "buildNumber": packageInfo.buildNumber,
        "deviceType": Platform.isIOS
            ? "ios"
            : Platform.isAndroid
                ? "android"
                : "",
      },
      success: (Result res) async {
        if (Platform.isAndroid) {
          AndroidUpdate.show(
            version: res.data["version"],
            url: res.data["downloadUrl"],
          );
        } else if (Platform.isIOS) {
          IOSUpdate.show(
            version: res.data["version"],
            url: res.data["downloadUrl"],
          );
        }
      },
      failure: (res) async {
        if (isToast) {
          EasyLoading.showToast("当前已经是最新版本");
        }
        if (Platform.isAndroid) {
          AndroidUpdate.delApk();
        }
      },
    );
  }
}
